//使用require.context
let files = require.context("@/pages", true, /\.vue$/)
let repeatRoutes = files.keys().map(path => {
    let regExp = /(\/index\.vue|\.vue)$/
    let com = files(path).default;
    path = path.replace(regExp, "").substring(1)
    // console.log((path))
    return {
        //重定向
        redirect: com.redirect ?? null,
        //具名路由
        name: com.name ?? path.substring(1).split("/").join("-"), //具名路由
        meta: com.meta ?? {}, //路由原信息
        path: path.toLowerCase(),
        component: () => import("@/pages" + path)
    }
});

//repeatRoutes转换成树形
const convertTree = (repeatRoutes) => {
    let treeRoues = [];
    repeatRoutes.forEach(route => {
        let pathArr = route.path.substring(1).split('/');
        route.id = pathArr.join("-")
        if (pathArr.length > 1) {
            let pidArr = [...pathArr] //浅拷贝
            pidArr.pop()
            route.pid = pidArr.join("-")
        }
    });
//吧平铺数据变成嵌套的树形数据
    repeatRoutes.forEach(route => {
        let parent = repeatRoutes.find(v => v.id === route.pid)
        if (parent) {
            if (!parent.children) {
                parent.children = []
            }
            route.path = route.path.split("/").pop()
            parent.children.push(route)
        } else {
            treeRoues.push(route)
        }
    })
    return treeRoues;
}

let result = convertTree(repeatRoutes)


export default result;